package fun.tan90.easy.binlog.plugin.webhook.service.impl;


import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.Forest;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.webhook.model.WebhookParams;
import lombok.extern.slf4j.Slf4j;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/15 14:41
 */
@Slf4j
public class WebhookPluginService implements PluginService {

    @Override
    public boolean test(String params) {
        WebhookParams webhookParams = JSONUtil.toBean(params, WebhookParams.class);

        ForestRequest<?> forestRequest = Forest.post(webhookParams.getUrl())
                .contentTypeJson()
                .setBackend("okhttp3")
                .maxRetryCount(webhookParams.getMaxRetryCount())
                .setConnectTimeout(webhookParams.getConnectTimeout() * 1000)
                .setReadTimeout(webhookParams.getReadTimeout() * 1000)
                .successWhen((req, res) -> {
                    log.debug("successWhen noException:{} StatusCode:{}", res.noException(), res.getStatusCode());
                    return res.noException() && res.statusIsNot(405) && res.statusIsNot(404);
                });
        String authType = webhookParams.getAuthType();
        if ("1".equals(authType)) {
            WebhookParams.BasicAuth basicAuth = webhookParams.getBasicAuth();
            forestRequest.addHeader("Authorization", "Basic " + Base64.encode(basicAuth.getUsername() + ":" + basicAuth.getPassword()));
        }
        ForestResponse<?> forestResponse = forestRequest.executeAsResponse();
        return forestResponse.isSuccess();
    }
}
